<template>
  <div class="verification-container">
    <input
      v-for="(code, index) in verificationCodes"
      :key="index"
      v-model="verificationCodes[index]"
      @input="handleInput(index, $event)"
      @keydown="handleKeyDown(index, $event)"
      maxlength="1"
      type="password"
      class="verification-input"
    />
  </div>
</template>

<script setup>
import { ref, defineEmits, nextTick } from 'vue';

const emits = defineEmits(['emailCode']);
const verificationCodes = ref(['', '', '', '', '', '', '', '']);

const handleInput = (index, event) => {
  const { value } = event.target;
  verificationCodes.value[index] = value;

  // 判断是否输入完成
  if (verificationCodes.value.join('').length === 8) {
    emits('emailCode', verificationCodes.value.join(''));
  }

  // 自动跳到下一个输入框
  if (value && index < verificationCodes.value.length - 1) {
    const nextInput = event.target.nextElementSibling;
    if (nextInput) {
      nextTick(() => {
        nextInput.focus();
      });
    }
  }
};
const handleKeyDown = (index, event) => {
  // 处理删除操作
  if (event.key === 'Backspace' && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling;
    if (prevInput) {
      nextTick(() => {
        prevInput.focus();
      });
    }
  }
};
</script>

<style lang="less" scoped>
.verification-container {
  display: flex;
  margin-top: 65px;
}

.verification-input {
  width: 21px;
  height: 42px;
  margin-right: 11px;
  text-align: center;
  font-size: 20px;
  border: 1px solid #ebebeb;
  border-radius: 5px;
  color: #fff;

  &:last-child {
    margin-right: 0;
  }
}

.verification-input:focus {
  outline: none;
  // border-color: #007bff;
  // box-shadow: 0 0 5px #007bff;
}
</style>
